var realm_name = ""; //域名
var name = "";
var portNum = 1;
var area = "";
var totalAddressData = 0; //地址数据总条数
var totalPage = 0;
var pageSize = 200; //每页数据条数
var pageIndex = 1; //当前页数
var firstInstallCost = 0; //初装费
var memberPhoneCount = 3; //成员手机号的数量
var businessCode = "ACBZ13422"; //资费代码
var custIDCard = ""; //客户身份证号码
var netAttr = ""; //合作模式
var broadType = "1"; //宽带类型 0:爱家小区, 1:优家小区
var second = 0;
var groupId = getParamValue("group_id");
var empCode = getParamValue("EmpCode"); //操作工号
var cityCodeId = getParamValue("CityCodeId"); //地区编码
var bandWidth = "";
var addressPageNumber = 1;
var addressList = new Array();
var addressNoMoreData = false;
var addressParamsArray; //宽带开户接口所需的本页面提供的参数集合（小区地址信息相关参数）
var passedPhone = "";

var reg = Constants.cmccMobileReg; //移动号码段

var getUrlParameter = function() {
  realm_name = getParamValue("Domains");
  var bd_name = getParamValue("BdName");
  if (bd_name) {
    name = decodeURIComponent(bd_name);
  }
  custIDCard = getParamValue("custIDCard");
  groupId = getParamValue("group_id");
  cityCodeId = getParamValue("CityCodeId");
  empCode = getParamValue("EmpCode");
}

var initInstallDate = function() {
  var dd = new Date();
  var di = +dd + 1000 * 60 * 60 * 24; //48小时之后
  dd = new Date(di);
  var month = (dd.getMonth() + 1) < 10 ? ("0" + (dd.getMonth() + 1).toString()) : (dd.getMonth() + 1).toString();
  var date = dd.getDate() <= 9 ? ("0" + dd.getDate().toString()) : dd.getDate().toString();
  var ds = dd.getFullYear().toString() + "-" + month + "-" + date;
  //console.log("date = " + ds);
  document.getElementById("install_time").value = ds;
  //document.getElementById("install-date").valueAsDate = dd;
}

/* 初始化日期控件 start*/
var mydatetime = $(".form_datetime").datetimepicker({
  language: 'zh-CN', //语言设置，默认使用英语 'en' ,额外添加amazeui.datetimepicker.zh-CN.js,注意编码格式charset="UTF-8"
  format: 'yyyy-mm-dd hh:ii', //日期格式：接受String,默认为mm/dd/yyyy
  autoclose: true, //日期选定以后是否自动关闭日期选择器, 默认为 true (仅在 days(今日) 视图有效)。
  todayBtn: true, //是否显示今日视图
  todayHighlight: true, //是否高亮显示今天的日期
  minuteStep: 15, //设置分钟视图时间间隔数，默认为 5
  pickerPosition: 'bottom-right' //'bottom-right' (默认)、'bottom-left'、'top-right'、'top-left'
});
mydatetime.on('show', function(ev) { //绑定事件
  var height = $("#change-height-div").height();
  $("#change-height-div").height(height + 100);
});
mydatetime.on('hide', function(ev) { //绑定事件
  var height = $("#change-height-div").height();
  $("#change-height-div").height(height - 100);
});


var invalidParam = function(val, errorMsg) {
  console.log("val=" + val + ",msg=" + errorMsg);
  if (val) {
    return false;
  } else {
    showAlertMessage(errorMsg);
    return true;
  }
}

var checkInputParams = function() {  
  if (invalidParam($("#customer_phone").val(), "请填写手机号码")) {
    return false;
  }
  console.log("passedPhone=" + passedPhone + ",customer_phone=" + $("#customer_phone").val());
  if (passedPhone != $("#customer_phone").val()) {
    showAlertMessage("手机号" + $("#customer_phone").val() + "未通过校验，请先短信校验");
    $("#verify_code").val('');
    return false;
  }
  if (invalidParam($("#address_selected").html(), "请选择装机地址")) {
    return false;
  }
  if (invalidParam($("#address_detail").val(), "请填写详细地址")) {
    return false;
  }  
  if(!invalidInstallTime()){
    return false;
  }
  return true;
}

var invalidInstallTime = function(){
  var today = new Date();
  installDate = new Date($('#install_time').val())
  if(installDate<today){
    showAlertMessage("安装时间不能早于今天");
    return false;
  }else{
    return true;
  }
}

var submit_fun = function() {
  if (!checkInputParams()) {
    return;
  }

  if (portNum <= 0) {
    showAlertMessage("小区宽带无剩余端口，无法办理宽带开户业务");
    return;
  }
  showLoadingModal('正在检查宽带参数，请稍候...');
  checkBlPhone($("#customer_phone").val());
}

var generateParamsAndGotoConfirm = function(idAddress, custID, custAddress, idValiddate, idICCID) {
  var install_time = $("#install_time").val();
  //如果安装时间为空，则默认为当前提交时间的24小时之后
  if (install_time == "" || install_time == null) {
    var d = new Date();
    d = new Date(d);
    d = +d + 1000 * 60 * 60 * 24;
    d = new Date(d);
    var year = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes();
    install_time = year;
  }

  var customer_name = $("#customer_name").val();
  var customer_phone = $("#customer_phone").val();
  var verify_code = $("#verify_code").val();
  var city = $("#city").val();
  var county_town = $("#county_town").val().split("|")[0];  
  var address_detail = $("#address_detail").val();
  var address_id = $("#buildaddresId").val();
  var accessType = $("#access_type").html();
  var link_way = $("#link_way").val();

  var broadband_id = $("#broadband_id").val();
  var broadband_name = $("#broadband_name").val();

  params = getParams();
  params += "&install_time=" + install_time;
  params += "&Phone=" + customer_phone + "&cust_name=" + customer_name + "&id_iccid=" + idICCID;
  params += "&id_address=" + idAddress + "&cust_id=" + custID + "&cust_address=" + address_detail + "&id_validdate=" + idValiddate;
  for (i = 0; i < addressParamsArray.length; i++) {
    params += "&" + addressParamsArray[i];
  }  
  window.location.replace("broadband_confirm.html?" + params);
}

var closeLoadingModal = function() {
  $('#modal').modal('close');
}

var showLoadingModal = function(info) {
  $("#modal-info").html(info);
  $('#modal').modal('open');
}

var smsDisabledInterval = function() {
  if (second > 1) {
    $("#send_sms_btn").val("重新发送(" + second + ")");
    second--;
  } else {
    clearSmsInterval();
  }
}

var clearSmsInterval = function() {
  clearInterval(smsInterval);
  $("#send_sms_btn").removeClass('am-disabled');
  $("#send_sms_btn").val('获取验证码');
}

var onClickSendSmsBtn = function() {
  $("#customer_name").val('');
  $("#customer_name_display").val('');
  phoneNumber = $("#customer_phone").val();
  if (!phoneNumber || isNaN(phoneNumber) || phoneNumber.length != 11) {
    showAlertMessage("请填写正确的手机号码");
    return;
  }
  $("#send_sms_btn").addClass('am-disabled');
  second = 60;
  $("#send_sms_btn").html(second + "秒");
  smsInterval = setInterval(smsDisabledInterval, 1000);
  checkCustRealChk(phoneNumber);
}

var onClickVerifySmsBtn = function() {
  console.log("onClickVerifySmsBtn");
  phoneNumber = $("#customer_phone").val();
  if (!phoneNumber || isNaN(phoneNumber) || phoneNumber.length != 11) {
    showAlertMessage("请填写正确的手机号码");
    return;
  }
  verifyCode= $("#verify_code").val();
  if (!verifyCode) {
    showAlertMessage("请填写验证码");
    return;
  }
  verifySms(phoneNumber, verifyCode);
}

//修改订购按钮状态
var enable_submit = function(status) {
  if (status) {
    $("#submit_btn").removeClass("am-btn-default").addClass("am-btn-primary");
    $("#submit_btn").removeAttr('disabled');
    $("#submit_btn").bind("click", submit_fun);
  } else {
    $("#submit_btn").removeClass("am-btn-primary").addClass("am-btn-default");
    $("#submit_btn").attr('disabled');
    $("#submit_btn").unbind("click", submit_fun);
  }
};

/*
获取宽带业务数据
*/
var loadBroadband = function() {
  var params = {
    "id": getParamValue("id")
  };
  $.ajax({
    type: "post",
    url: "../../broadbandH5/broadband",
    data: params,
    dataType: "json",
      headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
      console.log(data);
      console.log("broadband.broad_type = " + data.broad_type);
      if (data) {
        name = data.name;
        $("#broad_name_text").html(name);
        $("#broadband_name").html(name);

        broadType = data.broad_type; //宽带类型 0:爱家小区, 1:优家小区
        if (broadType == "0") {
          netAttr = 2; //合作模式 2:广电，0、1、3、4、5：非广电
        }
        if (data.business_code) {
          businessCode = data.business_code;
        }
        if (data.first_install_cost) {
          firstInstallCost = data.first_install_cost;
        }
        if (data.member_phone_count) {
          memberPhoneCount = data.member_phone_count;
        }
      }
    },
    error: function(textStatus) {
      console.info("getBroadbandById request error");
    }
  });
}

/*
 通过城市获取区县数据
 */
var loadArea = function() {
  $(".am-topbar").removeClass("am-hide");
  showLoadingModal('加载中...');
  var params = {
    "groupId": groupId,
    "userId": getParamValue("userId")
  };
  $.ajax({
    type: "post",
    url: "../../broadbandH5/areas",
    data: params,
    dataType: "json",
      headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
      console.log(data);
      if (data.resultCode == 1000) {
        $("#city option:first").text(data.data.city);
        $("#city option:first").val(data.data.city);
        $("#city").selected('disable');        
        showArea(JSON.parse(data.data.areas));
      } else {
        setTimeout('showAlertMessage("' + data.message + '")', 50);
      }
    },
    error: function(textStatus) {
      $(".am-topbar").addClass("am-hide");
      showAlertMessage("请求服务器出错，请联系管理员！");
    },
    complete: function() {
      closeLoadingModal();
    }
  });
};


var showArea = function(data) {
  var $tpl = $('#county_town_tpl');
  var source = $tpl.text();
  var template = Handlebars.compile(source);
  var myData = {
    list: data
  };
  var html = template(myData);
  $("#county_town").html(html);
};

/*
  验证是否实名认证
  */
var checkCustRealChk = function(tel) {
  showLoadingModal("获取验证码中...");
  $('#modal').modal({
    closeViaDimmer: false
  });
  var data = {
    "BODY": {
      "PHONE_NO": tel
    }
  };
  var url = Constants.apiV2HostRest + "sQChkCustReal";
  console.log("esb.callSChkSvcNoSc.url=" + url);
  console.log("esb.callSChkSvcNoSc.data=" + JSON.stringify(data));
  $.ajax({
    type: "post",
    url: url,
    data: JSON.stringify(data),
    contentType: "application/json",
    dataType: "json",
      headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
      console.log("data:" + JSON.stringify(data));
      closeLoadingModal();
      if (data && data.ROOT.RETURN_CODE == 0) {
        if (data.ROOT.OUT_DATA.REAL_FLAG == "Y") {
          //保存认证信息          
          custIDCard = data.ROOT.OUT_DATA.ID_ICCID;
          console.log("custIDCard=" + custIDCard);
          custName = data.ROOT.OUT_DATA.CUST_NAME;
          $("#customer_name").val(custName);
          if(custName!=null){
            $("#customer_name_display").val("*"+custName.substr(1));  
          }          
          sendSmsCode(tel); //发送验证码
        } else {
          clearSmsInterval();
          showAlertMessage("号码" + tel + "还未实名认证，不能办理宽带业务！");
        }
      } else {
        clearSmsInterval();
        closeLoadingModal();
        showAlertMessage(data.ROOT.USER_MSG);
      }
    },
    error: function(textStatus) {
      closeLoadingModal();
      clearSmsInterval();
      showAlertMessage("请求服务器出错，请联系管理员！");
    }
  });  
}

/*
发送验证码
*/
var sendSmsCode = function(tel) {
  console.log("sendSmsCode:" + tel)
  var url = Constants.apiV2Host + "sms/send?phoneNumber=" + tel + "&smsType=9&empCode=" + getParamValue("EmpCode");
  console.log('url:' + url);
  $.ajax({
    type: "get",
    url: url,
    contentType: "application/json",
    dataType: "json",
      headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
      closeLoadingModal();
      if (data.ResultCode == 1000) {
        showAlertMessage("短信已发送，请注意查收");
      } else {
        showAlertMessage(data.Message);
      }
    },
    error: function(textStatus) {
      clearSmsInterval();
      closeLoadingModal();
      showAlertMessage("请求服务器出错，请联系管理员！");
    }
  });
}

/*
验证是否有合账接口
*/
var checkBlPhone = function(tel) {
  var url = Constants.apiV2HostRest + "sChkBlPhone";
  var data = {
    "BODY": {
      "GROUP_ID": getParamValue("group_id"),
      "REGION_ID": getParamValue("CityCodeId"),
      "PHONE_NO": tel
    }
  };
  console.log("esb.callSChkSvcNoSc.url=" + url);
  console.log("esb.callSChkSvcNoSc.data=" + JSON.stringify(data));
  $.ajax({
    type: "post",
    url: url,
    data: JSON.stringify(data),
    contentType: "application/json",
    dataType: "json",
      headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
      console.log("data:" + JSON.stringify(data));
      console.log(data);
      closeLoadingModal();
      if (data && data.ROOT.RETURN_CODE == 0) {
        outData = data.ROOT.OUT_DATA;
        if (outData.HZ_FLAG == "N") {
          idAddress = outData.ID_ADDRESS;
          custID = outData.CUST_ID;
          custAddress = outData.CUST_ADDRESS;
          idValiddate = outData.ID_VALIDDATE;
          idICCID = outData.ID_ICCID;
          generateParamsAndGotoConfirm(idAddress, custID, custAddress, idValiddate, idICCID);
        } else {
          showAlertMessage("该号码已办理家庭合账/集团合账业务，不能办理融合宽带业务，请更换办理号码");
        }
      } else {
        showAlertMessage(data.ROOT.DETAIL_MSG);
      }
    },
    error: function(textStatus) {
      closeLoadingModal();
      showAlertMessage("请求服务器出错，请联系管理员！");
    }
  });
}

/*
发送验证码
*/
var verifySms = function(tel, code) {
  showLoadingModal("正在校验，请稍候...");
  var url = Constants.apiV2Host + "sms/validate?phoneNumber=" + tel + "&smsCode=" + code + "&smsType=9&empCode=" + getParamValue("EmpCode");
  console.log('url:' + url);
  $.ajax({
    type: "get",
    url: url,
    contentType: "application/json",
    dataType: "json",
      headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
      closeLoadingModal();
      console.info(data);
      if (data && data.ResultCode != 1000) {
        showAlertMessage("短信验证码校验失败！" + data.Message);
        passedPhone = "";
        $('#verify_code').val('');
        return;
      }
      showAlertMessage("短信验证码校验成功！");
      /*记录校验后的号码*/
      passedPhone = $("#customer_phone").val();
      enable_submit(true);
    },
    error: function(textStatus) {
      closeLoadingModal();
      showAlertMessage("短信验证码校验失败！");
      passedPhone = "";
    }
  });
};

var showAlertMsg = function(message) {
  console.log("showAlertMsg.message=" + message);
  $("#bd-alert-content").html(message);
  var options = {
    closeViaDimmer: false,
    dimmer: true
  };
  $("#bd-alert").modal('open');
}

var showAlertMessage = function(message) {
  console.log("showAlertMessage");
  setTimeout('showAlertMsg("' + message + '")', 50);
}

var closeAlertMessage = function() {
    $("#bd-alert").modal('close');
  }
  /*
     地址搜索按钮
     */
var searchAddress = function(pageNumber) {
  showLoadingBar($("#loadingAddress"), true);
  var area = $("#address_keyword").val();
  if (!area) {
    area = $("#area option:selected").text();
  }
  var minRownNum = (pageNumber - 1) * 8 + 1;
  var maxRowNum = pageNumber * 8;

  var data = {
    "BODY": {
      "PHONE_NO": getParamValue("phonenumber"),
      "COMMON_INFO": {
          "PROVINCE_GROUP": ""
      },
      "Data": {
        "Param": {
          "REGION_ID": getParamValue("CityCodeId"),
          "Amount": "8",
          "TypeFlag": "0",
          "AddressID": "",
          "AddressName": "",
          "AreaName": area,
          "AreaAddress": "",
          "VillageName": "",
          "JDName": "",
          "StreetName": "",
          "ResType": "1",
          "MINROWNUM": minRownNum,
          "MAXROWNUM": maxRowNum,
          "DistrictCode": $("#county_town option:selected").val().split("|")[0],
          "NetAttr": "",
          "GD_ADDRESSID": ""
        }
      }
    }
  };
  var url = Constants.apiV2HostRest + "sQryBandAddress";
  console.log("url:" + url);
  console.log("data:" + JSON.stringify(data));

  $.ajax({
    type: "post",
    url: url,
    contentType: "application/json",
    data: JSON.stringify(data),
    dataType: "json",
      headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
      showLoadingBar($("#loadingAddress"), false);
      console.log(JSON.stringify(data));
      var root = data.ROOT;
      if (root) {
        if (root.RETURN_CODE == 0) {
          showAddressResult(root);
        } else if (root.RETURN_CODE == 'E409005000') {
          addressNoMoreData = true;
          if (addressList.length > 0) {
            showAddressError('没有更多了', true);
          } else {
            showAddressError('根据您的输入，没有找到相关的小区信息!', true);
          }
        }
      } else {
        addressNoMoreData = true;
        showAddressError('根据您的输入，没有找到相关的小区信息!', true);
      }
    },
    error: function(textStatus) {
      showLoadingBar($("#loadingAddress"), false);
      showAddressError('请求服务器出错，请联系管理员！', true);
    }
  });
}

/*
自定义模板规则：两个值作比较
*/
Handlebars.registerHelper('compare', function(left, operator, right, options) {
  if (arguments.length < 3) {
    throw new Error('Handlerbars Helper "compare" needs 2 parameters');
  }
  var operators = {
    '==': function(l, r) {
      return l == r;
    },
    '===': function(l, r) {
      return l === r;
    },
    '!=': function(l, r) {
      return l != r;
    },
    '!==': function(l, r) {
      return l !== r;
    },
    '<': function(l, r) {
      return l < r;
    },
    '>': function(l, r) {
      return l > r;
    },
    '<=': function(l, r) {
      return l <= r;
    },
    '>=': function(l, r) {
      return l >= r;
    },
    'typeof': function(l, r) {
      return typeof l == r;
    }
  };

  if (!operators[operator]) {
    throw new Error('Handlerbars Helper "compare" doesn\'t know the operator ' + operator);
  }

  var result = operators[operator](left, right);

  if (result) {
    return options.fn(this);
  } else {
    return options.inverse(this);
  }
});

var setList = function(list, orgList) {
  var netAttr = orgList.NetAttr;
  // 当前为爱家宽带（0）需netAttr为2；当前为优家宽带（1）需netAttr为非2
  if ((broadType == "0" && netAttr == "2") || (broadType == "1" && netAttr != "2")) {
    list.push(orgList);
  }
};

var getFiltedData = function(data) {
  var orgList = data.OUT_DATA.OUT_DATA.Param;
  var list = new Array();
  if (orgList) {
    if (orgList instanceof Array) {
      var len = orgList.length;
      for (var i = 0; i < len; i++) {
        var addr = orgList[i];
        setList(list, addr);
        // var netAttr = addr.NetAttr;
        // // 当前为爱家宽带（0）需netAttr为2；当前为优家宽带（1）需netAttr为非2
        // if((broadType == "0" && netAttr == "2") || (broadType == "1" && netAttr != "2")){
        //   list.push(addr);
        // }
      }
    } else {
      setList(list, orgList);
    }
  }

  return list;
};


var itemOnClick = function(object, clickFunc) {
  $(object).off("click"); //取消li事件
  /*li事件*/
  $(object).on("click", function() {
    var $siblingsNode = $(this).siblings();
    var primaryClass = "select-item";
    var defaultColor = "#fff";
    var selectColor = "#0c79b1";

    if ($siblingsNode.hasClass(primaryClass)) {
      $siblingsNode.removeClass(primaryClass);
      $siblingsNode.css("background-color", defaultColor);
    }
    if ($(this).hasClass(primaryClass)) {
      $(this).removeClass(primaryClass);
      $(this).css("background-color", defaultColor);
    } else {
      $(this).addClass(primaryClass);
      $(this).css("background-color", selectColor);
    }
    clickFunc(this);
    event.stopPropagation();
  });
}

var clearAddressListHtml = function() {
  $("#address-list").children('li').remove();
  $("#address-list").children('div').remove();
}

var showAddressError = function(msg, show) {
  console.log('showAddressError:' + msg + ",show=" + show);
  if (show) {
    $("#error-msg").removeClass('am-hide');
    $("#error-msg").html(msg);
  } else {
    if (!$("#error-msg").hasClass('am-hide')) {
      $("#error-msg").addClass('am-hide');
    }
    $("#error-msg").html('');
  }
}

var showAddressResult = function(data) {
  console.log("showAddressResult");
  var list = getFiltedData(data);

  console.log("list.length=" + list.length);
  if (list.length == 0) {
    addressPageNumber--;
    console.log("addressPageNumber=" + addressPageNumber);
  }

  for (var i = 0; i < list.length; i++) {
    list[i].memberNameEx = list[i].memberName + list[i].officalName + ":" + list[i].productNo;
    addressList.push(list[i]);
  }
  var $cust_list = $('#amz-address-list');
  var source = $cust_list.text();
  var template = Handlebars.compile(source);
  var data = {
    addressList: addressList
  };
  if (addressList.length == 0) {
    showAddressError('未找到符合条件的小区，请输入您的具体地址（小区详细地址）', true);
  } else {
    showAddressError('', false);
  }
  clearAddressListHtml();
  var html = template(data);
  $cust_list.before(html);
  itemOnClick("#address-list > li", addressItemClick);
  $("#cust_contactor").attr("placeholder", "请选择地址");
}

var addressItemClick = function(object) {
  var address = $(object).find("div[name='address']").html();
  var buildaddresId = $(object).find("input[name='buildaddresId']").val();
  var areaCode = $(object).find("input[name='areaCode']").val();
  var areaAddress = $(object).find("input[name='areaAddress']").val();
  var add_coop_mode = $(object).find("input[name='netAttr']").val();
  var workFlag = $(object).find("input[name='workFlag']").val();
  var areaName = $(object).find("input[name='areaName']").val();
  var accessType = $(object).find("input[name='accessType']").val();
  var region_value = $("#county_town").val();

  addressParamsArray = new Array; //初始化/清空参数集合
  addressParamsArray.push("build_addr_id=" + buildaddresId);
  addressParamsArray.push("add_expand_addr=" + address);
  addressParamsArray.push("address_id=" + areaCode);
  addressParamsArray.push("address=" + region_value.split("|")[1] + "|" + areaAddress);
  addressParamsArray.push("add_coop_mode=" + add_coop_mode);
  addressParamsArray.push("work_flag=" + workFlag);
  addressParamsArray.push("area_name=" + areaName);
  addressParamsArray.push("add_inter_mode=" + accessType);
  addressParamsArray.push("region_value=" + region_value.split("|")[0]);
  bandWidth = $(object).find("input[name='bandWidth']").val();
  addressParamsArray.push("bandWidth=" + bandWidth);

  // TODO 根据选择的装机地址，先判断宽带域名，若为 “tfgkd”则无需校验，均可办理;
  // 若为其它域名，则需要通过接口（sQBroadPortNum）获取该小区端口数，大于0的才能办理,否则提示该小区无可用端口
  if ("tfgkd" != realm_name) {
    getBroadPortNum(address);
  } else {
    portNum = 1000;
  }

  // TODO 做同步处理
  $("#address_selected").html(address);
  $("#address_detail").val(address);
  $("#accessType").val($(object).find("input[name='accessType']").val());
  $("#buildaddresId").val($(object).find("input[name='buildaddresId']").val());
  $("#netAttr").val($(object).find("input[name='netAttr']").val());
  $("#areaCode").val($(object).find("input[name='areaCode']").val());
  $("#areaName").val($(object).find("input[name='areaName']").val());
  $("#access_type").html($(object).find("input[name='accessType']").val());

  $('#address-alert').modal('close');
}


/*
 获取宽带业务数据
 */
var getBroadPortNum = function(standard_address) {
  showLoadingModal("正在检查宽带参数，请稍候...");

  var url = Constants.apiV2HostRest + "sQBroadPortNum";
  var data = {
    "BODY": {
        "PHONE_NO": getParamValue("phonenumber"),
        "STANDARD_ADDRESS": standard_address,
        "LOGIN_NO": getParamValue("EmpCode"),
        "GROUP_ID": getParamValue("group_id")
    }
  };
  console.log("esb.callSChkSvcNoSc.url=" + url);
  console.log("esb.callSChkSvcNoSc.data=" + JSON.stringify(data));
  $.ajax({
    type: "post",
    url: url,
    data: JSON.stringify(data),
    contentType: "application/json",
    dataType: "json",
      headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
      console.log("data:" + JSON.stringify(data));
      console.log(data);
      closeLoadingModal();
      if (data) {
        var root = data.ROOT;
        if (root.RETURN_CODE == 0 && root.OUT_DATA != undefined && root.OUT_DATA.IS_VERIFY == "Y") {
          if (root.OUT_DATA.PORT_NUM > 0) {
            portNum = root.OUT_DATA.PORT_NUM;
            showAlertMessage("该小区剩余端口数为" + portNum);
          } else {
            portNum = 0;
            showAlertMessage("该小区剩余端口数为0，不能办理宽带开户业务");
          }
        } else {
          showAlertMessage(root.USER_MSG);
        }
      }
    },
    error: function(textStatus) {
      console.info("getBroadPortNum request error");
      showAlertMessage("检查宽带参数错误，请稍后再试");
      closeLoadingModal();
    }
  });
}

var initAddressSroll = function() {
  var $doc = $("#address-list-div");
  $doc.scroll(function() {
    scrollHeight = $(this)[0].scrollHeight;
    height = $doc.height();
    scorollTop = Math.ceil($doc.scrollTop());
    if ((scrollHeight - height - scorollTop) <= 30) {
      var $msg = $("#no-data-msg");
      if (!$msg.hasClass("am-hide")) {
        $msg.addClass("am-hide");
      }
      console.log("addressPageNumber=" + addressPageNumber);
      if (addressNoMoreData == false) {
        addressPageNumber++;
        searchAddress(addressPageNumber);
      }
    }
  });
}

var clearSelectedAddress = function() {
  $("#access_type").html('');
  $("#address_selected").html('');
  $("#address_detail").val('');
}

$(function() {
  initInstallDate();
  initAddressSroll();
  $("#send_sms_btn").on('click', onClickSendSmsBtn);
  $("#verify_sms_btn").on('click', onClickVerifySmsBtn);
  // $("#submit_btn").bind("click", submit_fun);
  $("#address").on('click', function() {
    var options = {
      closeViaDimmer: false
    };
    $("#address-alert").modal(options);
  });
  $("#address_detail").on('click', function() {
    var options = {
      closeViaDimmer: false
    };
    $('#bd-alert-address-detail').val($("#address_detail").val());
    $("#bd-address-detail-modal").modal(options);
  });
  $("#bd-address-detail-save-btn").on('click', function(){
     $("#address_detail").val($('#bd-alert-address-detail').val());
  });
  $("#address_undo_btn").on('click', function() {
    clearSelectedAddress();
  });
  $("#county_town").on('change', function() {
    clearSelectedAddress();
    clearAddressListHtml();
  });
  $("#query-address-btn").on('click', function() {
    clearAddressListHtml();
    showAddressError('', false);
    addressPageNumber = 1;
    addressList = [];
    addressNoMoreData = false;
    searchAddress(addressPageNumber);
  });
  getUrlParameter();
  $("#broad_name_text").html(name);
  $("#broadband_name").html(name);
  loadArea();
})